import { Injectable, NestInterceptor, CallHandler } from '@nestjs/common';
import { Observable, map } from 'rxjs';

interface Data<T> {
  body: T;
}

@Injectable()
export class Response<T = any> implements NestInterceptor {
  intercept(context, next: CallHandler): Observable<Data<T>> {
    return next.handle().pipe(
      map((data) => {
        const { body = {}, code = '200', message = '' } = data;
        let messageText = '';
        let success = false;
        switch (code) {
          case '200':
            messageText = '成功';
            success = true;
            break;
          default:
            messageText = message;
            success = false;
            break;
        }
        return {
          body,
          code,
          message: messageText,
          success,
        };
      }),
    );
  }
}
